package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.cache.HomePageCache;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwNoticeService;
import com.xuanwei.dao.entity.XwNotice;
import com.xuanwei.dao.mapper.XwNoticeMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-08-02
 */
@Service
public class XwNoticeServiceImpl extends ServiceImpl<XwNoticeMapper, XwNotice> implements IXwNoticeService {

    @Override
    public void add(Integer id, String content, Integer orderBy) {
        if (id == null) {
            if (findByName(content) != null) {
                throw new XwException("已存在相同词汇");
            }
            XwNotice notice = new XwNotice();
            notice.setContent(content);
            notice.setOrderBy(orderBy);
            notice.setUpdateTime(LocalDateTime.now());
            notice.setCreateTime(LocalDateTime.now());
            save(notice);
        } else {
            XwNotice one = getOne(new QueryWrapper<XwNotice>().select("id").eq("id", id));
            if (one == null) {
                throw new XwException("数据不存在");
            }

            XwNotice byName = findByName(content);
            if (byName != null && byName.getId() != id) {
                throw new XwException("已存在相同词汇");
            }
            one.setUpdateTime(LocalDateTime.now());
            one.setOrderBy(orderBy);
            one.setContent(content);
            updateById(one);
        }
    }
    private XwNotice findByName(String name) {
        return getOne(new QueryWrapper<XwNotice>().select("id").eq("content", name));
    }

    @Override
    public List<XwNotice> findAll() {
        return list(new QueryWrapper<XwNotice>().orderByAsc("order_by"));
    }

    @Override
    public void del(Integer id) {
        baseMapper.deleteById(id);
    }
}
